package axp.demo.livewlp;

import java.io.IOException;


import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Canvas;
import android.media.MediaPlayer;
import android.view.SurfaceHolder;

public class WallpaperPainterVideo extends Thread {
	SurfaceHolder mSurfaceHolder;
	Context mContext;
	MediaPlayer mMediaPlayer;
	private int video;
	/** State */
	private boolean wait;
	private boolean run;
	public WallpaperPainterVideo(SurfaceHolder surfaceHolder, Context context, int video) {
		mSurfaceHolder = surfaceHolder;
		mContext = context;
		mMediaPlayer = new MediaPlayer();
		mMediaPlayer.setLooping(true);
		this.video=video;
		// don't animate until surface is created and displayed
		this.wait = true;
		try {
	         AssetFileDescriptor afd = mContext.getAssets().openFd("video/video"+video+".mp4");
			mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
		//		mMediaPlayer.setDataSource("sdcard/video"+video+".mp4");
			mMediaPlayer.prepare();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Change the radius preference
	 */
/*	public void setVideo(int video) {
		this.video = video;
	}*/
	/**
	 * Pauses the livewallpaper animation
	 */
	public void pausePainting() {
		this.wait = true;
		synchronized(this) {
			this.notify();		
		}
	}

	/**
	 * Resume the livewallpaper animation
	 */
	public void resumePainting() {
		this.wait = false;
		synchronized(this) {
			this.notify();
		}
	}

	/**
	 * Stop the livewallpaper animation
	 */
	public void stopPainting() {
		this.run = false;
		synchronized(this) {
			this.notify();
		}
	}

	public void startPainting() {
		mMediaPlayer.setScreenOnWhilePlaying(false);
		try {
			mMediaPlayer.setDisplay(mSurfaceHolder);
		} catch (UnsupportedOperationException ex) {
			ex.printStackTrace();
			return;
		}

		mMediaPlayer.start();
	}
	public void setVideo(int video) {
		// TODO Auto-generated method stub
		this.video=video;
		
	}
	@Override
	public void run() {
		this.run = true;
		Canvas c = null;
		while (run) {
			try {
				c = this.mSurfaceHolder.lockCanvas(null);
				synchronized (this.mSurfaceHolder) {
				//	doDraw(c);
				}
			} finally {
				if (c != null) {
					this.mSurfaceHolder.unlockCanvasAndPost(c);
				}
			}
			// pause if no need to animate
			synchronized (this) {
				if (wait) {
					try {
						wait();
					} catch (Exception e) {}
				}
			}
		}
}}
